package com.dcivision.dms.web;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.sql.Connection;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.core.DmsWinClientOperartionManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractMaintAction;

/**
  MaintDmsWindowsClientAction

  This class is the for Dms Windows Client.

  @author      jerry zhou
  @company     DCIVision Limited
  @creation date   01/08/2005
  @version     $Revision: 1.5.2.2 $
  */

public class MaintDmsWindowsClientAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.5.2.2 $";
  protected Log log = LogFactory.getLog(this.getClass().getName());
  
  //design operation type
  protected static String DMS_CREATE = "DMS_CREATE";
  protected static String DMS_UPDATE = "DMS_UPDATE";
  protected static String DMS_DEL = "DMS_DEL";
  protected static String DMS_CHECKIN = "DMS_CHECKIN";
  protected static String DMS_CHECKOUT = "DMS_CHECKOUT";
  protected static String DMS_COPY = "DMS_COPY";
  protected static String DMS_MOVE = "DMS_MOVE";
  protected static String DMS_VERSION = "DMS_VERSION";
  protected static String DMS_ADVSEARCH = "DMS_ADVSEARCH";
  protected static String DMS_KEYWORDSEARCH = "DMS_KEYWORDSEARCH";
  protected static String DMS_DISPLAYINDEX = "DMS_DISPLAYINDEX";
  protected static String DMS_EDITINDEX = "DMS_EDITINDEX";
  
  //design worng type
  protected static String PARASE_XML_WRONG = "PARASEXMLWRONG";
  protected static String CREATE_XML_WRONG = "CREATEXMLWRONG";
  protected static String UNKONW_WRONG = "UNKONWWRONG";
  
  String resultCode = "00";

  
  public String getFunctionCode() {
	return null;
  }

  
  public String getMajorDAOClassName() {
	return null;
  }
  
  /**
   * execute - Override the parent function.
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return
   * @throws ServletException
   */
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    MaintDmsWindowsClientForm actionForm = (MaintDmsWindowsClientForm) form;
    resultCode = "00";
    
    try {  	  
      this.loadParaDoc(request,actionForm);
  	}catch (ApplicationException ee) {
  	  if(this.PARASE_XML_WRONG.equals(ee.getMsgCode())){  		
  		resultCode = "01";//parse xml wrong
  	  }else if(this.CREATE_XML_WRONG.endsWith(ee.getMsgCode())){
  		resultCode = "02";// create xml wrong
  	  }else if(DmsErrorConstant.DUPLICATE_FILE_NAME.equals(ee.getMsgCode())){
  		resultCode = "03";// duplicate file name
  	  }else if(DmsErrorConstant.HAVE_NO_FUNCTION_PERMISSION.equals(ee.getMsgCode())){
  		resultCode = "04";// no permission
  	  }else if(this.UNKONW_WRONG.equals(ee.getMsgCode())){
        resultCode = "11";// unknown wrong
  	  }else{
  		resultCode = "11";// unknown wrong
  	  }
	  this.loadWrongMessage(resultCode, request);
	}catch (Exception eee){
	  resultCode = "11";// unknown wrong
	}
  	return mapping.findForward(GlobalConstant.NAV_MODE_EDIT);
  }
  
  /**
   * main method:get all DmsDocument tree according the specific user privillege,
   * then write to a xml called odma.xml 
   */
  public void loadParaDoc(HttpServletRequest request,ActionForm form) throws ApplicationException{ 
   Document doc = newDocument();
   documentOperation(doc,request,form); 
   writeToXml(doc,request); 
  }
  
  private void loadWrongMessage(String resultCode,HttpServletRequest request) throws ApplicationException{ 
    Document doc = newDocument();
    printWrongMessage(doc,request,resultCode); 
    writeToXml(doc,request); 
  }
  
  /**
   *  new a empty Document
   */
  private Document newDocument() throws ApplicationException{
    try{
	  DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      return builder.newDocument(); 
    }catch (Exception ee){
      throw new ApplicationException(this.UNKONW_WRONG);
    }
  }
  
  /**
   *  write Document to a xml file.
   */
  private void writeToXml(Document doc,HttpServletRequest request) throws ApplicationException{
    try{
	  Source source = new DOMSource(doc); 
      StringWriter writer=new StringWriter();
      StreamResult result = new StreamResult(writer);	   
      Transformer xformer = TransformerFactory.newInstance().newTransformer();
      xformer.transform(source, result);
      StringBuffer writerBuffer=new StringBuffer();
      writerBuffer.append(writer.toString());
      request.setAttribute("WriteXml",writer.toString());
    }catch (Exception e){
      throw new ApplicationException(this.CREATE_XML_WRONG);
    }
  }
  
  /**
   *  create DmsDocument action.
   */
  private void documentOperation(Document doc,HttpServletRequest request,ActionForm form) throws ApplicationException{
	MaintDmsWindowsClientForm actionForm = (MaintDmsWindowsClientForm) form;
	SessionContainer sessionContainer = this.getSessionContainer(request);
	Connection conn = this.getConnection(request);
	
	DmsWinClientOperartionManager dmsWinClient = new DmsWinClientOperartionManager(sessionContainer,conn);
	FormFile formFile = actionForm.getUploadXmlFile();
    
    if (this.DMS_CREATE.equals(actionForm.getOperationType())){
      try {
        this.parseFormCreateXmlDataToForm(actionForm); 
        DmsDocument newDocument = dmsWinClient.createDocument(actionForm);
        this.commit(request);
        this.createXml(doc,request,newDocument,this.DMS_CREATE);
      }catch (ApplicationException appEx) {
        this.rollback(request);
        throw appEx;
      }
  	}else if(this.DMS_UPDATE.equals(actionForm.getOperationType())){
  	  try {
  	    this.parseFormCreateXmlDataToForm(actionForm);
  	    DmsDocument newDocument = dmsWinClient.updateDocument(actionForm);
        this.commit(request);
        this.createXml(doc,request,newDocument,this.DMS_UPDATE);
  	  }catch (ApplicationException appEx) {
        this.rollback(request);
        throw appEx;
      }
  	}else if(this.DMS_DEL.equals(actionForm.getOperationType())){
  	  try{    
  		this.parseFormCreateXmlDataToForm(actionForm);
        dmsWinClient.delDocument(actionForm);
        this.commit(request);
        this.createXml(doc,request,this.DMS_DEL);
  	  }catch (ApplicationException appEx) {
        this.rollback(request);
        throw appEx;
      }
	}else if(this.DMS_CHECKIN.equals(actionForm.getOperationType())){
	  try{
	    this.parseFormCreateXmlDataToForm(actionForm);
        dmsWinClient.checkInDocument(actionForm);
	    this.commit(request);	  
	    DmsDocument newDocument = dmsWinClient.checkOutDocument(actionForm);
	    this.createXml(doc,request,newDocument,this.DMS_CHECKIN);
	  }catch (ApplicationException appEx) {
	    this.rollback(request);
	    throw appEx;
	  }
	}else if(this.DMS_CHECKOUT.equals(actionForm.getOperationType())){
	  try{
	    this.parseFormCreateXmlDataToForm(actionForm);
	    DmsDocument newDocument = dmsWinClient.checkOutDocument(actionForm);
	    this.commit(request);
	    this.createXml(doc,request,newDocument,this.DMS_CHECKOUT);
	  }catch (ApplicationException appEx) {
	   this.rollback(request);
	   throw appEx;
	  }
	}else if(this.DMS_COPY.equals(actionForm.getOperationType())){
	  try{
	    this.parseFormCreateXmlDataToForm(actionForm);
	    dmsWinClient.copyDocument(actionForm);
	    this.commit(request);
	    this.createXml(doc,request,this.DMS_COPY);
	  }catch (ApplicationException appEx) {
	    this.rollback(request);
	    throw appEx;
	  }
	}else if(this.DMS_MOVE.equals(actionForm.getOperationType())){
	  try{  
		this.parseFormCreateXmlDataToForm(actionForm);
	    dmsWinClient.moveDocument(actionForm);
	    this.commit(request);
	    this.createXml(doc,request,this.DMS_MOVE);
	  }catch (ApplicationException appEx) {
        this.rollback(request);
        throw appEx;
      }
	}else if(this.DMS_VERSION.equals(actionForm.getOperationType())){
	  try{  
        this.parseFormCreateXmlDataToForm(actionForm);
        ArrayList list = (ArrayList) dmsWinClient.versionDocument(actionForm);
	    this.commit(request);
	    this.createListXml(doc,request,this.DMS_VERSION,list);
	  }catch (ApplicationException appEx) {
        this.rollback(request);
        throw appEx;
      }
	}else if(this.DMS_ADVSEARCH.equals(actionForm.getOperationType())){
	  try{  
	    ListDmsDocumentForm searchForm = new ListDmsDocumentForm();
	    this.parseFormCreateXmlDataToForm(searchForm,formFile);
	    ArrayList list = (ArrayList) dmsWinClient.advSearchDocument(searchForm);
	    this.commit(request);
	    this.searchListXml(doc,request,this.DMS_ADVSEARCH,list);
	  }catch (ApplicationException appEx) {
        this.rollback(request);
        throw appEx;
      }
	}else if(this.DMS_KEYWORDSEARCH.equals(actionForm.getOperationType())){
	  try{  
		ListDmsDocumentForm searchForm = new ListDmsDocumentForm();
        this.parseFormCreateXmlDataToForm(searchForm,formFile);
	    ArrayList list = (ArrayList) dmsWinClient.keywordSearchDocument(searchForm);
	    this.commit(request);
	    this.searchListXml(doc,request,this.DMS_KEYWORDSEARCH,list);
	  }catch (ApplicationException appEx) {
        this.rollback(request);
        throw appEx;
      }
	}else if(this.DMS_DISPLAYINDEX.equals(actionForm.getOperationType())){
	  try{  
	    this.parseFormCreateXmlDataToForm(actionForm);
	    String resultStr = dmsWinClient.indexDocument(actionForm);
	    this.commit(request);
	    this.indexStrXml(doc,request,this.DMS_DISPLAYINDEX,resultStr);
	  }catch (ApplicationException appEx) {
        this.rollback(request);
        throw appEx;
      }
	}else if(this.DMS_EDITINDEX.equals(actionForm.getOperationType())){
      try{  
		this.parseFormCreateXmlDataToForm(actionForm);
	    String resultStr = dmsWinClient.indexDocument(actionForm);
	    this.commit(request);
	    this.indexStrXml(doc,request,this.DMS_EDITINDEX,resultStr);
	  }catch (ApplicationException appEx) {
        this.rollback(request);
        throw appEx;
      }
	}else{
	  throw new ApplicationException(this.PARASE_XML_WRONG);
	}
  }
  
  private void addParaUserXml(Document rootDocument,Element parentElement,HttpServletRequest request) throws ApplicationException{ 
    SessionContainer sessionContainer = this.getSessionContainer(request);
    
    Element user = rootDocument.createElement("user");
    user.setAttribute("loginName",sessionContainer.getUserRecord().getLoginName()); 
	java.util.Date currentDate = new java.util.Date(); 
	Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	user.setAttribute("createTime",format.format(currentDate));
	parentElement.appendChild(user);
  }
  
  private void createXml(Document doc, HttpServletRequest request, DmsDocument newDocument ,String opertTionType) throws ApplicationException{
    try{
	  Element response = doc.createElement("response");
      response.setAttribute("module","paradoc"); 
      doc.appendChild(response);
      addParaUserXml(doc,response,request);
    
      Element client = doc.createElement("client");
      client.setAttribute("operationType",opertTionType);
      client.setAttribute("resultCode",resultCode);
      response.appendChild(client); 
    
      Element document = doc.createElement("document");
      document.setAttribute("documentID",TextUtility.formatIntegerObj(newDocument.getID()));
      document.setAttribute("documentName",newDocument.getDocumentName());
      document.setAttribute("documentType",newDocument.getDocumentType());    
      document.setAttribute("itemStatus",newDocument.getItemStatus());
      client.appendChild(document);
    }catch (Exception e){
      throw new ApplicationException(this.CREATE_XML_WRONG);
    }
  }
  
  private void createXml(Document doc, HttpServletRequest request, String opertTionType) throws ApplicationException{
    try{
	  Element response = doc.createElement("response");
      response.setAttribute("module","paradoc"); 
      doc.appendChild(response);
      addParaUserXml(doc,response,request);
	    
      Element client = doc.createElement("client");
      client.setAttribute("operationType",opertTionType);
      client.setAttribute("resultCode",resultCode);
      response.appendChild(client); 
    }catch (Exception e){
      throw new ApplicationException(this.CREATE_XML_WRONG);
    }
  }
  
  private void createListXml(Document doc, HttpServletRequest request, String opertTionType, ArrayList list) throws ApplicationException{
    try{
	  DmsVersion dmsVersion = (DmsVersion)list.get(0);
      SessionContainer sessionContainer = this.getSessionContainer(request);
	  Connection conn = this.getConnection(request);
      DmsWinClientOperartionManager dmsWinClient = new DmsWinClientOperartionManager(sessionContainer,conn);
	
      Element response = doc.createElement("response");
      response.setAttribute("module","paradoc"); 
      doc.appendChild(response);
      addParaUserXml(doc,response,request);
		    
      Element client = doc.createElement("client");
      client.setAttribute("operationType",opertTionType);
      client.setAttribute("resultCode",resultCode);
      client.setAttribute("documentID",TextUtility.formatIntegerObj(dmsVersion.getDocumentID()));    
      response.appendChild(client); 
    
      for(int i=0; i<list.size(); i++){
        dmsVersion = (DmsVersion)list.get(i);
      
        Element versionList = doc.createElement("versionList");
        versionList.setAttribute("ver_number",dmsVersion.getVersionNumber());
        versionList.setAttribute("ver_label",dmsVersion.getVersionLabel());
        versionList.setAttribute("size",TextUtility.formatIntegerObj(dmsVersion.getItemSize()));
        versionList.setAttribute("reference",dmsVersion.getReferenceNo());
        versionList.setAttribute("description",dmsVersion.getDescription());
        versionList.setAttribute("creator",dmsWinClient.getUserNameByID(dmsVersion.getCreatorID()));
         versionList.setAttribute("createDate",TextUtility.formatTimestamp(dmsVersion.getCreateDate()));
        client.appendChild(versionList);
      }
    }catch (Exception e){
      throw new ApplicationException(this.CREATE_XML_WRONG);
    }
  }
  
  private void searchListXml(Document doc, HttpServletRequest request, String opertTionType, ArrayList list) throws ApplicationException{
    try{
      SessionContainer sessionContainer = this.getSessionContainer(request);
      Connection conn = this.getConnection(request);
      DmsWinClientOperartionManager dmsWinClient = new DmsWinClientOperartionManager(sessionContainer,conn);
      DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    
      Element response = doc.createElement("response");
      response.setAttribute("module","paradoc"); 
      doc.appendChild(response);
      addParaUserXml(doc,response,request);
			    
      Element client = doc.createElement("client");
      client.setAttribute("operationType",opertTionType);
      client.setAttribute("resultCode",resultCode);  
      response.appendChild(client); 
    
      int listCount = 0;
      if(!Utility.isEmpty(list)){
    	listCount = list.size();
      }
    
      Element searchList = doc.createElement("searchResultList");
      searchList.setAttribute("listCount",TextUtility.formatInteger(listCount));
      client.appendChild(searchList);
      
	    
      for(int i=0; i<list.size(); i++){
        DmsDocument dmsDocument = (DmsDocument)list.get(i);
        DmsRoot dmsRoot = docRetrievalManager.getDmsRootByDocumentID(dmsDocument.getID());	
        String isPbulic = "true";
        String fatherID = "";
        
        if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(dmsRoot.getRootName())) { 
          isPbulic = "false";
        }

        String location = "";
        List ancestorList = new ArrayList();
        try{
          ancestorList = docRetrievalManager.getAllParentDocumentList(dmsDocument.getID());
          location = docRetrievalManager.getLocationPath(dmsDocument.getParentID());
        }catch(Exception e){
          log.error(e, e);          
        }
        for (int k=0; k<ancestorList.size(); k++){
          DmsDocument docTep = (DmsDocument)ancestorList.get(k);
          if (k!=0){
            fatherID += ",";
          }
          fatherID  += TextUtility.formatIntegerObj(docTep.getID());
        }
        //log.debug(dmsDocument.getID()) ;        
        Element document = doc.createElement("document");        
        document.setAttribute("documentID",TextUtility.formatIntegerObj(dmsDocument.getID()));
        document.setAttribute("documentName",dmsDocument.getDocumentName());
        document.setAttribute("rootID",TextUtility.formatIntegerObj(dmsDocument.getRootID()));
        document.setAttribute("parentID",TextUtility.formatIntegerObj(dmsDocument.getParentID()));
        document.setAttribute("documentType",dmsDocument.getDocumentType());        
        document.setAttribute("location",location);
        //document.setAttribute("size",TextUtility.formatIntegerObj(dmsDocument.getItemSize()));
        document.setAttribute("status",dmsDocument.getItemStatus());
        document.setAttribute("updateDate",TextUtility.formatTimestamp(dmsDocument.getUpdateDate()));
        document.setAttribute("updater",dmsWinClient.getUserNameByID(dmsDocument.getUpdaterID()));
        document.setAttribute("isPbulic",isPbulic);
        document.setAttribute("fatherID",fatherID);
        searchList.appendChild(document);
      }
    }catch (Exception e){
      log.error(e, e);
      throw new ApplicationException(this.CREATE_XML_WRONG);
    }
  }
  
  private void indexStrXml(Document doc, HttpServletRequest request, String opertTionType, String resultStr) throws ApplicationException{
	try{
      Element response = doc.createElement("response");
      response.setAttribute("module","paradoc"); 
      doc.appendChild(response);
      addParaUserXml(doc,response,request);
				    
      Element client = doc.createElement("client");
      client.setAttribute("operationType",opertTionType);
      client.setAttribute("resultCode",resultCode);  
      response.appendChild(client); 
    	    
      Element resultString = doc.createElement("resultString");
      client.appendChild(resultString);
      resultString.setAttribute("content",resultStr);
	}catch (Exception e){
	  throw new ApplicationException(this.UNKONW_WRONG);
	}
  }
  
  private void printWrongMessage(Document doc, HttpServletRequest request, String resultCode) throws ApplicationException{
	try{
	  Element response = doc.createElement("response");
	  response.setAttribute("module","paradoc"); 
      doc.appendChild(response);
      addParaUserXml(doc,response,request);
		  
      Element resultWrong = doc.createElement("resultWrong"); 
      resultWrong.setAttribute("resultCode",resultCode);
      response.appendChild(resultWrong);
	}catch (ApplicationException e){
      throw new ApplicationException(this.UNKONW_WRONG);
    }
		  	   
  }
  
  /** Parse the input */
  public void parseFormCreateXmlDataToForm(MaintDmsWindowsClientForm form ) throws ApplicationException {
    try {
      // Get an efficient reader for the file
      String opMode = "" ;
      String sCurFunctionCode = "";
      String documentID = "" ;
      String documentName = "";
      String parentID = ""  ;
      String rootID = "" ;
      String referenceNo = ""  ;
      String description = "";       
      String documentType = "";
      String createType = "" ;
      String priority = "" ;
      String effectiveEndDate = "" ;
      String destinationID = "";
      
      String searchFolder = "";
      String documentNameOption = "";
      String documentNameExactMatch = "";
      String documentTypeOption = "";
      String effectiveDateOption = "";
      String effectiveStartDate = "";
      String createDateOption = "";
      String createDate = "";
      String createToDate = "";
      String updateDateOption = "";
      String updateDate = "";
      String updateToDate = "";
      String priorityOption = "";
      String priorityExactMatch = "";
      String referenceNoOption = "";
      String referenceNoExactMatch = "";
      String descriptionOption = "";
      String descriptionExactMatch = "";
      
      String content = "";
      
      InputStream inputStream = null;
      FormFile formFile = null;
      formFile = form.getUploadXmlFile();
      inputStream = formFile.getInputStream();
      InputSource input = new InputSource();
      input.setByteStream(inputStream);      
      // Create an Document node as the root for the output.
      DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
      org.w3c.dom.Document indexFile = docBuilder.parse(input);

      /* Parse Document tag for the use name and login pwd */
      NodeList doclist = indexFile.getElementsByTagName("form");
      Node docNode = doclist.item(0);
      if (docNode != null) {
        if ("form".equals(docNode.getNodeName())) {
          try { documentID = ((Element)docNode).getAttributeNode("documentID").getValue(); } catch (Exception ignore) {}
          try { parentID = ((Element)docNode).getAttributeNode("parentID").getValue(); } catch (Exception ignore) {}
          try { rootID = ((Element)docNode).getAttributeNode("rootID").getValue(); } catch (Exception ignore) {}
          try { referenceNo = ((Element)docNode).getAttributeNode("referenceNo").getValue(); } catch (Exception ignore) {}
          try { description = ((Element)docNode).getAttributeNode("description").getValue(); } catch (Exception ignore) {}
          try { documentType = ((Element)docNode).getAttributeNode("documentType").getValue(); } catch (Exception ignore) {}
          try { documentName = ((Element)docNode).getAttributeNode("documentName").getValue(); } catch (Exception ignore) {}          
          try { createType = ((Element)docNode).getAttributeNode("createType").getValue(); } catch (Exception ignore) {}
          try { priority = ((Element)docNode).getAttributeNode("priority").getValue(); } catch (Exception ignore) {}
          try { effectiveStartDate = ((Element)docNode).getAttributeNode("effectiveStartDate").getValue(); } catch (Exception ignore) {}
          try { effectiveEndDate = ((Element)docNode).getAttributeNode("effectiveEndDate").getValue(); } catch (Exception ignore) {}
          try { opMode = ((Element)docNode).getAttributeNode("opMode").getValue(); } catch (Exception ignore) {}
          try { sCurFunctionCode = ((Element)docNode).getAttributeNode("sCurFunctionCode").getValue(); } catch (Exception ignore) {}
          try { destinationID = ((Element)docNode).getAttributeNode("destinationID").getValue(); } catch (Exception ignore) {}
          
          try { searchFolder = ((Element)docNode).getAttributeNode("searchFolder").getValue(); } catch (Exception ignore) {}
          try { documentNameOption = ((Element)docNode).getAttributeNode("documentNameOption").getValue(); } catch (Exception ignore) {}
          try { documentNameExactMatch = ((Element)docNode).getAttributeNode("documentNameExactMatch").getValue(); } catch (Exception ignore) {}
          try { documentTypeOption = ((Element)docNode).getAttributeNode("documentTypeOption").getValue(); } catch (Exception ignore) {}
          try { effectiveDateOption = ((Element)docNode).getAttributeNode("effectiveDateOption").getValue(); } catch (Exception ignore) {}
          try { createDateOption = ((Element)docNode).getAttributeNode("createDateOption").getValue(); } catch (Exception ignore) {}
          try { createDate = ((Element)docNode).getAttributeNode("createDate").getValue(); } catch (Exception ignore) {}
          try { createToDate = ((Element)docNode).getAttributeNode("createToDate").getValue(); } catch (Exception ignore) {}
          try { updateDateOption = ((Element)docNode).getAttributeNode("updateDateOption").getValue(); } catch (Exception ignore) {}
          try { updateDate = ((Element)docNode).getAttributeNode("updateDate").getValue(); } catch (Exception ignore) {}
          try { updateToDate = ((Element)docNode).getAttributeNode("updateToDate").getValue(); } catch (Exception ignore) {}
          try { priorityOption = ((Element)docNode).getAttributeNode("priorityOption").getValue(); } catch (Exception ignore) {}
          try { priorityExactMatch = ((Element)docNode).getAttributeNode("priorityExactMatch").getValue(); } catch (Exception ignore) {}
          try { referenceNoOption = ((Element)docNode).getAttributeNode("referenceNoOption").getValue(); } catch (Exception ignore) {}
          try { referenceNoExactMatch = ((Element)docNode).getAttributeNode("referenceNoExactMatch").getValue(); } catch (Exception ignore) {}
          try { descriptionOption = ((Element)docNode).getAttributeNode("descriptionOption").getValue(); } catch (Exception ignore) {}
          try { descriptionExactMatch = ((Element)docNode).getAttributeNode("descriptionExactMatch").getValue(); } catch (Exception ignore) {}
          try { content = ((Element)docNode).getAttributeNode("content").getValue(); } catch (Exception ignore) {}
          
          if(!"".equals(documentID)){
            form.setID(documentID);
          }
          if(!"".equals(createType)){
            form.setCreateType(createType);
          }
          if(!"".equals(priority)){
            form.setPriority(priority);
          }          
          if(!"".equals(documentType)){
            form.setDocumentType(documentType);
          }                    
          if(!"".equals(parentID)){
            form.setParentID(parentID);
          }
          if(!"".equals(rootID)){
            form.setRootID(rootID);
          }
          if(!"".equals(referenceNo)){
            form.setReferenceNo(referenceNo);
          }
          if(!"".equals(description)){
            form.setDescription(description);
          }
          if(!"".equals(documentName)){
            form.setDocumentName(documentName);
          }
          if(!"".equals(effectiveStartDate)){
              form.setEffectiveStartDate(effectiveStartDate);
          }
          if(!"".equals(effectiveEndDate)){
            form.setEffectiveEndDate(effectiveEndDate);
          }
          if(!"".equals(opMode)){
            form.setOpMode(opMode);
          }
          if(!"".equals(sCurFunctionCode)){
            form.setSCurFunctionCode(sCurFunctionCode);
          }
          if(!"".equals(destinationID)){
            form.setDestinationID(destinationID);
          }
          
          
          if(!"".equals(searchFolder)){
            form.setSearchFolder(searchFolder);
          }
          if(!"".equals(documentNameOption)){
            form.setDocumentNameOption(documentNameOption);
          }
          if(!"".equals(documentNameExactMatch)){
            form.setDocumentNameExactMatch(documentNameExactMatch);
          }
          if(!"".equals(documentTypeOption)){
            form.setDocumentTypeOption(documentTypeOption);
          }
          if(!"".equals(effectiveDateOption)){
            form.setEffectiveDateOption(effectiveDateOption);
          }
          if(!"".equals(createDateOption)){
            form.setCreateDateOption(createDateOption);
          }
          if(!"".equals(createDate)){
            form.setCreateDate(createDate);
          }
          if(!"".equals(createToDate)){
            form.setCreateToDate(createToDate);
          }
          if(!"".equals(updateDateOption)){
            form.setUpdateDateOption(updateDateOption);
          }
          if(!"".equals(updateDate)){
            form.setUpdateDate(updateDate);
          }
          if(!"".equals(updateToDate)){
            form.setUpdateToDate(updateToDate);
          }
          if(!"".equals(priorityOption)){
            form.setPriorityOption(priorityOption);
          }
          if(!"".equals(priorityExactMatch)){
            form.setPriorityExactMatch(priorityExactMatch);
          }
          if(!"".equals(referenceNoOption)){
            form.setReferenceNoOption(referenceNoOption);
          }
          if(!"".equals(referenceNoExactMatch)){
            form.setReferenceNoExactMatch(referenceNoExactMatch);
          }
          if(!"".equals(descriptionOption)){
            form.setDescriptionOption(descriptionOption);
          }
          if(!"".equals(descriptionExactMatch)){
            form.setDescriptionExactMatch(descriptionExactMatch);
          }
          if(!"".equals(content)){
            form.setContent(content);
          }
        }
      }
    } catch (Exception e) {
      throw new ApplicationException(this.PARASE_XML_WRONG);
    } 
  }
  
  /** Parse the input 
 * @throws IOException 
 * @throws FileNotFoundException 
 * @throws IOException 
 * @throws FileNotFoundException 
 * @throws ParserConfigurationException 
 * @throws ParserConfigurationException 
 * @throws SAXException 
 * @throws SAXException */
  public void parseFormCreateXmlDataToForm(ListDmsDocumentForm form,FormFile formFile) throws  ApplicationException{
    try {
      // Get an efficient reader for the file
      String opMode = "" ;
      String documentName = "";
      String parentID = ""  ;
      String rootID = "" ;
      String referenceNo = ""  ;
      String description = "";       
      String documentType = "";
      String priority = "" ;
      String effectiveEndDate = "" ;
      
      String searchFolder = "";
      String documentNameOption = "";
      String documentNameExactMatch = "";
      String documentTypeOption = "";
      String effectiveDateOption = "";
      String effectiveStartDate = "";
      String createDateOption = "";
      String createDate = "";
      String createToDate = "";
      String updateDateOption = "";
      String updateDate = "";
      String updateToDate = "";
      String priorityOption = "";
      String priorityExactMatch = "";
      String referenceNoOption = "";
      String referenceNoExactMatch = "";
      String descriptionOption = "";
      String descriptionExactMatch = "";
      
      String keyword = "";
      
      InputStream inputStream = null;
      inputStream = formFile.getInputStream();
      InputSource input = new InputSource();
      input.setByteStream(inputStream);      
      // Create an Document node as the root for the output.
      DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
      org.w3c.dom.Document indexFile = docBuilder.parse(input);

      /* Parse Document tag for the use name and login pwd */
      NodeList doclist = indexFile.getElementsByTagName("form");
      Node docNode = doclist.item(0);
      if (docNode != null) {
        if ("form".equals(docNode.getNodeName())) {
          //try { documentID = ((Element)docNode).getAttributeNode("documentID").getValue(); } catch (Exception ignore) {}
          try { parentID = ((Element)docNode).getAttributeNode("parentID").getValue(); } catch (Exception ignore) {}
          try { rootID = ((Element)docNode).getAttributeNode("rootID").getValue(); } catch (Exception ignore) {}
          try { referenceNo = ((Element)docNode).getAttributeNode("referenceNo").getValue(); } catch (Exception ignore) {}
          try { description = ((Element)docNode).getAttributeNode("description").getValue(); } catch (Exception ignore) {}
          try { documentType = ((Element)docNode).getAttributeNode("documentType").getValue(); } catch (Exception ignore) {}
          try { documentName = ((Element)docNode).getAttributeNode("documentName").getValue(); } catch (Exception ignore) {}          
          //try { createType = ((Element)docNode).getAttributeNode("createType").getValue(); } catch (Exception ignore) {}
          try { priority = ((Element)docNode).getAttributeNode("priority").getValue(); } catch (Exception ignore) {}
          try { effectiveStartDate = ((Element)docNode).getAttributeNode("effectiveStartDate").getValue(); } catch (Exception ignore) {}
          try { effectiveEndDate = ((Element)docNode).getAttributeNode("effectiveEndDate").getValue(); } catch (Exception ignore) {}
          try { opMode = ((Element)docNode).getAttributeNode("opMode").getValue(); } catch (Exception ignore) {}
          //try { sCurFunctionCode = ((Element)docNode).getAttributeNode("sCurFunctionCode").getValue(); } catch (Exception ignore) {}
          //try { destinationID = ((Element)docNode).getAttributeNode("destinationID").getValue(); } catch (Exception ignore) {}
          
          try { searchFolder = ((Element)docNode).getAttributeNode("searchFolder").getValue(); } catch (Exception ignore) {}
          try { documentNameOption = ((Element)docNode).getAttributeNode("documentNameOption").getValue(); } catch (Exception ignore) {}
          try { documentNameExactMatch = ((Element)docNode).getAttributeNode("documentNameExactMatch").getValue(); } catch (Exception ignore) {}
          try { documentTypeOption = ((Element)docNode).getAttributeNode("documentTypeOption").getValue(); } catch (Exception ignore) {}
          try { effectiveDateOption = ((Element)docNode).getAttributeNode("effectiveDateOption").getValue(); } catch (Exception ignore) {}
          try { createDateOption = ((Element)docNode).getAttributeNode("createDateOption").getValue(); } catch (Exception ignore) {}
          try { createDate = ((Element)docNode).getAttributeNode("createDate").getValue(); } catch (Exception ignore) {}
          try { createToDate = ((Element)docNode).getAttributeNode("createToDate").getValue(); } catch (Exception ignore) {}
          try { updateDateOption = ((Element)docNode).getAttributeNode("updateDateOption").getValue(); } catch (Exception ignore) {}
          try { updateDate = ((Element)docNode).getAttributeNode("updateDate").getValue(); } catch (Exception ignore) {}
          try { updateToDate = ((Element)docNode).getAttributeNode("updateToDate").getValue(); } catch (Exception ignore) {}
          try { priorityOption = ((Element)docNode).getAttributeNode("priorityOption").getValue(); } catch (Exception ignore) {}
          try { priorityExactMatch = ((Element)docNode).getAttributeNode("priorityExactMatch").getValue(); } catch (Exception ignore) {}
          try { referenceNoOption = ((Element)docNode).getAttributeNode("referenceNoOption").getValue(); } catch (Exception ignore) {}
          try { referenceNoExactMatch = ((Element)docNode).getAttributeNode("referenceNoExactMatch").getValue(); } catch (Exception ignore) {}
          try { descriptionOption = ((Element)docNode).getAttributeNode("descriptionOption").getValue(); } catch (Exception ignore) {}
          try {descriptionExactMatch = ((Element)docNode).getAttributeNode("descriptionExactMatch").getValue(); } catch (Exception ignore) {}
          
          try { keyword = ((Element)docNode).getAttributeNode("keyword").getValue(); } catch (Exception ignore) {}
          
          form.setPageOffset("10000");
          String[] searchPriority = TextUtility.splitString(priority,",");
          if(!"".equals(searchPriority)){
            form.setSearchPriority(searchPriority);
          }          
          if(!"".equals(documentType)){
            form.setDocumentType(documentType);
          }                    
          if(!"".equals(parentID)){
            form.setParentID(parentID);
          }
          if(!"".equals(rootID)){
            form.setRootID(rootID);
          }
          if(!"".equals(referenceNo)){
            form.setReferenceNo(referenceNo);
          }
          if(!"".equals(description)){
            form.setDescription(description);
          }
          if(!"".equals(documentName)){
            form.setDocumentName(documentName);
          }
          if(!"".equals(effectiveStartDate)){
              form.setEffectiveStartDate(effectiveStartDate);
          }
          if(!"".equals(effectiveEndDate)){
            form.setEffectiveEndDate(effectiveEndDate);
          }
          if(!"".equals(opMode)){
            form.setOpMode(opMode);
          }
          
          String[] searchFolderTep = TextUtility.splitString(searchFolder,",");
          if("false".equals(documentNameOption)){
            documentNameOption = "AND";	  
          }else{
        	documentNameOption = "OR";	   	  
          }
          if("false".equals(documentTypeOption)){
        	documentTypeOption = "AND";	  
          }else{
        	documentTypeOption = "OR";	   	  
          }
          if("false".equals(effectiveDateOption)){
        	effectiveDateOption = "AND";	  
          }else{
        	effectiveDateOption = "OR";	   	  
          }
          if("false".equals(createDateOption)){
        	createDateOption = "AND";	  
          }else{
        	createDateOption = "OR";	   	  
          }
          if("false".equals(updateDateOption)){
        	updateDateOption = "AND";	  
          }else{
        	updateDateOption = "OR";	   	  
          }
          if("false".equals(priorityOption)){
        	priorityOption = "AND";	  
          }else{
        	priorityOption = "OR";	   	  
          }
          if("false".equals(referenceNoOption)){
        	referenceNoOption = "AND";	  
          }else{
        	referenceNoOption = "OR";	   	  
          }
          if("false".equals(descriptionOption)){
        	descriptionOption = "AND";	  
          }else{
        	descriptionOption = "OR";	   	  
          }          
          
          
          if(!"".equals(searchFolderTep)){
            form.setSearchFolder(searchFolderTep);
          }
          if(!"".equals(documentNameOption)){
            form.setDocumentNameOption(documentNameOption);
          }
          if(!"".equals(documentNameExactMatch)){
            form.setDocumentNameExactMatch(TextUtility.parseBoolean(documentNameExactMatch));
          }
          if(!"".equals(documentTypeOption)){
            form.setDocumentTypeOption(documentTypeOption);
          }
          if(!"".equals(effectiveDateOption)){
            form.setEffectiveDateOption(effectiveDateOption);
          }
          if(!"".equals(createDateOption)){
            form.setCreateDateOption(createDateOption);
          }
          if(!"".equals(createDate)){
            form.setCreateDate(createDate);
          }
          if(!"".equals(createToDate)){
            form.setCreateToDate(createToDate);
          }
          if(!"".equals(updateDateOption)){
            form.setUpdateDateOption(updateDateOption);
          }
          if(!"".equals(updateDate)){
            form.setUpdateDate(updateDate);
          }
          if(!"".equals(updateToDate)){
            form.setUpdateToDate(updateToDate);
          }
          if(!"".equals(priorityOption)){
            form.setPriorityOption(priorityOption);
          }
          if(!"".equals(priorityExactMatch)){
            form.setPriorityExactMatch(TextUtility.parseBoolean(priorityExactMatch));
          }
          if(!"".equals(referenceNoOption)){
            form.setReferenceNoOption(referenceNoOption);
          }
          if(!"".equals(referenceNoExactMatch)){
            form.setReferenceNoExactMatch(TextUtility.parseBoolean(referenceNoExactMatch));
          }
          if(!"".equals(descriptionOption)){
            form.setDescriptionOption(descriptionOption);
          }
          if(!"".equals(descriptionExactMatch)){
            form.setDescriptionExactMatch(TextUtility.parseBoolean(descriptionExactMatch));
          }
          if(!"".equals(keyword)){
            form.setKeyword(keyword);
          }          
        }
      }
    }catch (Exception e) {
      throw new ApplicationException(this.PARASE_XML_WRONG);
    } 
  } 

}
